import cn from "@/utils/classnames";
import { View, Image } from "@tarojs/components";
import { useToggle } from "ahooks";
import React, { FC, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import Taro from "@tarojs/taro";
interface P {
  renderContent?: React.ReactNode;
}
let curIndex = 0;
export const DropdownMenuOffEmitter = (id?: string) => {
  Taro.eventCenter.trigger("drop_down", id);
};
export const DropdownMenu: FC<P> = props => {
  let [visible, { toggle, setLeft }] = useToggle();
  let [bottom, setBottom] = useState(9999);
  let id = useMemo(() => "drop_down_" + curIndex++, []);
  useEffect(() => {
    let hander = _id => {
      if (_id !== id) {
        setLeft();
      }
    };
    Taro.eventCenter.on("drop_down", hander);
    return () => {
      Taro.eventCenter.off("drop_down", hander);
    };
  }, [setLeft]);
  function getRect() {
    setTimeout(() => {
      Taro.createSelectorQuery()
        .select("#" + id)
        .boundingClientRect(res => {
          if (res) {
            if (res.bottom !== bottom) {
              setBottom(res.bottom);
            }
          } else {
            getRect();
          }
        })
        .exec();
    }, 10);
  }
  getRect();
  return (
    <View className={styles.wrap}>
      <View
        id={id}
        className={cn(styles.header, {
          [styles.active]: visible,
        })}
        onClick={e => {
          e.stopPropagation();
          DropdownMenuOffEmitter(id);
          toggle();
        }}
      >
        {props.children}
        <Image
          className={styles.arrow}
          src={"http://qihs5ygb9.hb-bkt.clouddn.com/mini/%E8%B7%AF%E5%BE%84%202%E5%A4%87%E4%BB%BD@2x.png"}
        ></Image>
      </View>

      {visible && (
        <View
          className={styles.dropWrap}
          style={{
            top: bottom + "px",
          }}
          onClick={() => {
            toggle();
          }}
        >
          <View className={styles.content} onClick={e => e.stopPropagation()}>
            {props.renderContent}
          </View>
        </View>
      )}
    </View>
  );
};
